package com.ezlcp.form.web.file;

import com.ezlcp.commons.tool.DateUtils;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author Elwin ZHANG
 * @description: 基础文件操作<br />
 * @date 2022/5/16 10:15
 */
public abstract class BaseFileOperator implements IFileOperator {

    /**
     * 构建路径
     * 1.当上下文有用户的情况返回
     * 租户ID/202206 这样的路径
     * 2.否则返回 20210508的路径。
     */
    protected String getRealPath() {
        // 上传的相对路径
        String tempPath = DateUtils.parseDateToStr("yyyyMM", new Date());
        String relFilePath = tempPath;
        String userId = ContextUtil.getCurrentUserId();
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(userId)) {
            if (StringUtils.isEmpty(tenantId)) {
                tenantId = "system";
            }
            relFilePath = tenantId + File.separator + tempPath;
        } else {
            relFilePath = "public" + File.separator + DateUtils.parseDateToStr("yyyyMMdd", new Date());
        }
        return relFilePath;
    }

    protected void addHeader(String fileName, HttpServletResponse response, boolean attachment) throws UnsupportedEncodingException {
        fileName = URLEncoder.encode(fileName, "UTF-8");

        String type = attachment ? "attachment" : "inline";
        response.setHeader("Content-Disposition", type + ";filename=" + fileName);
    }

}
